package com.xht.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xht.constants.SystemConstants;
import com.xht.domain.entity.LoginUser;
import com.xht.domain.entity.User;
import com.xht.mapper.MenuMapper;
import com.xht.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {


    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;

    /**
     * 自定义重写该方法
     * 用来 返回UserDetails对象
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询 用户信息
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>();
        queryWrapper.eq(User::getUserName, username);
        queryWrapper.eq(User::getStatus, SystemConstants.STATUS_NORMAL);
        User user = userMapper.selectOne(queryWrapper);
        //判断是否查询到用户，如果没有 则抛出异常
        if (Objects.isNull(user)) {
            throw new RuntimeException("用户不存在");
        }
        //用户存在，返回用户

        //还需要查询权限信息
        if (user.getType().equals(SystemConstants.ADMAIN)) { //如果该用户为 管理员的话,返回权限信息
            List<String> list = menuMapper.selectPermsByUserId(user.getId());
            return new LoginUser(user, list);
        }


        return new LoginUser(user, null);
    }
}
